﻿using System;
using System.Text;
using System.Windows.Forms;

namespace Module.FlowChart.RunAble.Code.View
{
    public partial class Form_Console : Form
    {
        public Form_Console()
        {
            InitializeComponent();
        }

        public Action<double> OnInput;

        public bool IsEndWithEnter = true;
        StringBuilder sb = new StringBuilder();
        bool Changed = false;
        public void Append(string str)
        {
            lock (this)
            {
                str = str.Replace("\n", "\r\n");
                sb.Append(str);
                IsEndWithEnter = str.EndsWith("\n");
                Changed = true;
            }
        }
        public void Clear()
        {
            lock (this)
            {
                sb.Clear(); IsEndWithEnter = true;
                Changed = true;
            }
        }

        private void BtnOk_Click(object sender, EventArgs e)
        {
            if (InputText.Text == "")
                return;
            double d;
            if (double.TryParse(InputText.Text, out d))
            {
                lock (this)
                {
                    if (!IsEndWithEnter)
                    {
                        sb.Append("\r\n");
                        IsEndWithEnter = true;
                    }
                    sb.Append("I N:");
                    sb.Append(d.ToString());
                    sb.Append("\r\n");
                    Changed = true;
                }
                OnInput?.Invoke(d);
                InputText.Text = "";
            }
            else
            {
                InputText.Text = "";
            }



        }

        private void InputText_TextChanged(object sender, EventArgs e)
        {

        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            lock (this)
            {
                if (Changed)
                {
                    ConsoleText.Text = sb.ToString();
                    Changed = false;
                }
            }
        }
    }
}
